package com.softer.chengxin.score.service.impl;

import com.softer.chengxin.common.domin.*;
import com.softer.chengxin.common.enums.*;
import com.softer.chengxin.common.util.DateFormatUtil;
import com.softer.chengxin.corp.dao.CorpDao;
import com.softer.chengxin.home.dao.MessageDao;
import com.softer.chengxin.home.domin.Message;
import com.softer.chengxin.scheduled.dao.ScheduledTaskDao;
import com.softer.chengxin.score.dao.SDManagerDao;
import com.softer.chengxin.score.entity.ScoreDetailVO;
import com.softer.chengxin.score.entity.ScoreRecord;
import com.softer.chengxin.score.service.SDManagerService;
import com.softer.chengxin.score.util.ScoreUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.StringValueExp;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author wangixnrui
 * @date 2018/10/12
 */
@Service
public class SDManagerServiceImpl implements SDManagerService {

    @Autowired
    private SDManagerDao managerDao;
    @Autowired
    private CorpDao corpDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private ScoreUtil scoreUtil;
    @Autowired
    private ScheduledTaskDao scheduledTaskDao;

    /**
     * 查询企业信用年度评价列表 条数
     *
     * @param loginName 登录名
     * @param qyName    企业名
     * @param dj        等级
     * @param year      年度
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult findByCondition(String loginName, String qyName, String dj, String year, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        if (StringUtils.isBlank(year)){
            //获取最近设置的定时任务
            String time = scheduledTaskDao.getTime();
            //获取主管部门定义的年份
             year = DateFormatUtil.getYear(time);
        }
        int count = managerDao.findByConditionCount(area, qyName, dj, year);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ScoreRecord> list = managerDao.findByCondition(area, qyName, dj, year, page);
        getAllScore(list);
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 计算各项总分
     *
     * @param list 分数集合
     */
    public void getAllScore(List<ScoreRecord> list) {
        for (ScoreRecord scoreRecord : list) {
            BigDecimal fmScore = scoreRecord.getFm01().add(scoreRecord.getFm02()).
                    add(scoreRecord.getFm03()).add(scoreRecord.getFm04()).
                    add(scoreRecord.getFm05()).add(scoreRecord.getFm06()).
                    add(scoreRecord.getFm07());
            scoreRecord.setAllfm(fmScore);
            BigDecimal jcScore = scoreRecord.getJc01().add(scoreRecord.getJc02()).
                    add(scoreRecord.getJc03()).add(scoreRecord.getJc04()).
                    add(scoreRecord.getJc05()).add(scoreRecord.getJc06()).
                    add(scoreRecord.getJc07());
            scoreRecord.setAlljc(jcScore);
            BigDecimal ylScore = scoreRecord.getYl01().add(scoreRecord.getYl02()).
                    add(scoreRecord.getYl03()).add(scoreRecord.getYl04()).
                    add(scoreRecord.getYl05()).add(scoreRecord.getYl06()).
                    add(scoreRecord.getYl07()).add(scoreRecord.getYl08());
            scoreRecord.setAllyl(ylScore);
        }
    }

    /**
     * 获取优良负面信息待审批列表
     *
     * @param loginName 登录名
     * @param infoType  信息种类
     * @param qyName    企业名
     * @param proName   项目名
     * @param state     状态
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult getScoreDetailList(String loginName, Integer infoType, String qyName, String proName, String state, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        //获取当前登录账号dicCode
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = managerDao.getScoreDetailListCount(infoType, area, qyName, proName, state);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreDetailList(infoType, area, page, qyName, proName, state);
        for (ScoreDetailVO s : list) {
            s.setProjectId(managerDao.findProNameById(s.getProjectId()));
        }
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 获取sp列表
     * @param loginName 登录名
     * @param infoType 信息种类
     * @param qyName 企业名
     * @param proName 项目名
     * @param page 页码
     * @return 结果
     */
    @Override
    public ManagerPageResult getSPList(String loginName, Integer infoType, String qyName, String proName, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String state = null;
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isNotBlank(dicCode)) {
            //3市  4区
            if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum()))) {
                state = String.valueOf(NumberEnum.NINE.getNum());
            } else if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
                state = "1,11";
            } else if(dicCode.equals(String.valueOf(NumberEnum.ONE_HUNDRED.getNum()))){
                state = "1,9,11";
            }
        }
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = managerDao.getScoreDetailListCount(infoType, area, qyName, proName, state);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreDetailList(infoType, area, page, qyName, proName, state);
        for (ScoreDetailVO s : list) {
            s.setProjectId(managerDao.findProNameById(s.getProjectId()));
        }
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 获取负面/优良信息 录入界面 的信息列表
     *
     * @param loginName 登录名
     * @param qyName    企业名
     * @param proName   项目名
     * @param infoType  信息种类
     * @param page      页码
     * @return 结果
     */
    @Override
    public ManagerPageResult getScoreAddList(String loginName, String qyName, String proName, Integer infoType, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        int count = managerDao.getScoreAddListCount(loginName, qyName, proName, infoType);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreAddList(loginName, qyName, proName, infoType, page);
        for (ScoreDetailVO s : list) {
            s.setProName(managerDao.findProNameById(s.getProjectId()));
        }
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 新增 保存 信息
     *
     * @param scoreDetailVO 实体
     * @return 结果
     */
    @Override
    public CommonResult addScore(ScoreDetailVO scoreDetailVO, String loginName) {
        scoreDetailVO.setAdder(loginName);
        //判断开始时间是否为空
        if (StringUtils.isBlank(scoreDetailVO.getEffectiveBeginTime()) || StringUtils.isBlank(scoreDetailVO.getEffectiveEndDate()) ) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        //公示期必须大于10天，当前时间和生效开始日期相差大于十天
        int flag = checkDate(scoreDetailVO.getEffectiveBeginTime());
        if (1 == flag) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "公示期最少10天，请选择十天后的时间！");
        }
        managerDao.addScore(scoreDetailVO);
        if (scoreDetailVO.getId() > NumberEnum.ZERO.getNum()) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 修改 保存 信息
     *
     * @param scoreDetailVO 实体
     * @return 结果
     */
    @Override
    public CommonResult update(ScoreDetailVO scoreDetailVO, String loginName) {
        //判断开始时间是否为空
        if (StringUtils.isBlank(scoreDetailVO.getEffectiveBeginTime()) || StringUtils.isBlank(scoreDetailVO.getEffectiveEndDate()) ) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        //公示期必须大于10天，当前时间和生效开始日期相差大于十天
        int flag = checkDate(scoreDetailVO.getEffectiveBeginTime());
        if (1 == flag) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "公示期最少10天，请选择十天后的时间！");
        }
        scoreDetailVO.setAdder(loginName);
        int ret = managerDao.update(scoreDetailVO);
        if (ret > NumberEnum.ZERO.getNum()) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 删除保存的信息
     *
     * @param id 信息id
     * @return 结果
     */
    @Override
    public CommonResult delete(Integer id) {
        int ret = managerDao.delete(id);
        if (ret > NumberEnum.ZERO.getNum()) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 获取该企业 年度 的 得分详细（优良信息，负面信息，基本信息）
     *
     * @param qyName             企业名
     * @param infoType           信息种类
     * @param effectiveBeginTime 公示开始时间
     * @param effectiveEndTime   公示结束时间
     * @param corpId             企业id
     * @param year               年度
     * @param loginName          登录名
     * @param page               页码
     * @return 结果集
     */
    @Override
    public ManagerPageResult getScoreDetailByYear(String loginName, String qyName, Integer infoType, String effectiveBeginTime, String effectiveEndTime, Integer corpId, String year, Page page) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String area = null;
        if (!Common.ADMIN.equals(loginName)) {
            area = corpDao.getDistinct(loginName);
        }
        int count = managerDao.getScoreDetailByYearCount(area, qyName, infoType, effectiveBeginTime, effectiveEndTime, corpId, year);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ScoreDetailVO> list = managerDao.getScoreDetailByYear(area, qyName, infoType, effectiveBeginTime, effectiveEndTime, corpId, year, page);
        jr.setDs(list);
        mpr.setJson(jr);
        mpr.setCount(count);
        return mpr;
    }

    /**
     * 通过id获取得分详细信息
     *
     * @param id id
     * @return 结果
     */
    @Override
    public ScoreDetailVO getDetailScore(Integer id) {

        return managerDao.getDetailScore(id);
    }

    /**
     * 获取变更信息列表
     * @param page      页码
     * @param qyName    企业名
     * @param proName   项目名
     * @param infoType  信息种类
     * @param loginName 登录名
     * @return 结果
     */
    @Override
    public ManagerPageResult getBianGengList(String loginName, Page page, String qyName, String proName, Integer infoType) {
        ManagerPageResult mpr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        //获取当前登录账号dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        //默认给个不存在的状态
        String state = "999";
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            //区管理账号
            state = "4,12";
        } else if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum()))) {
            //市管理账号
            state = String.valueOf(NumberEnum.TEN.getNum());
        } else if (dicCode.equals(String.valueOf(NumberEnum.ONE_HUNDRED.getNum()))) {
            //市管理账号
            state = String.valueOf("4,10,12");
        }
        Integer count = managerDao.getBianGengListCount(infoType, qyName, proName, loginName, state);
        if (count <= NumberEnum.ZERO.getNum()) {
            return common(mpr,jr);
        }
        List<ScoreDetailVO> list = managerDao.getBianGengList(infoType, page, qyName, proName, loginName, state);
        mpr.setCount(count);
        jr.setDs(list);
        mpr.setJson(jr);
        return mpr;
    }

    public ManagerPageResult common(ManagerPageResult mpr, JsonResult jr) {
        jr.setDs(new ArrayList());
        mpr.setJson(jr);
        mpr.setCount(NumberEnum.ZERO.getNum());
        return mpr;
    }

    /**
     * 删除负面/优良信息
     *
     * @param loginName 登录名（判断账号级别）
     * @param id        信息id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult delete(String loginName, Integer id) {
        int roleId = managerDao.getUserRoleId(loginName);
        if (roleId == NumberEnum.THREE.getNum() || roleId == NumberEnum.ONE.getNum() ) {
            Integer corpId = managerDao.getCorpId(id);
            ScoreDetailVO sd = managerDao.findScoreDetailById(id);
            int ret = managerDao.deleteScore(id);
            if (ret > NumberEnum.ZERO.getNum()) {
                //重新计算分数
                scoreUtil.updateRecord(corpId);
                if (sd.getInfoType() != null && sd.getState() != null && sd.getCorpId() != null) {
                    addMsg(sd.getInfoType(), sd.getState(), loginName, sd.getCorpId());
                }
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.NO_AUTHORITY);
    }

    /**
     * 新增  保存并公示  信息
     *
     * @param scoreDetailVO 参数
     * @param loginName     登录名
     * @return 结果
     */
    //TODO
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addAndPublicity(ScoreDetailVO scoreDetailVO, String loginName) {
        if (scoreDetailVO.getInfoType() == null || scoreDetailVO.getState() == null || scoreDetailVO.getCorpId() == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        //判断开始时间是否为空
        if (StringUtils.isBlank(scoreDetailVO.getEffectiveBeginTime()) || StringUtils.isBlank(scoreDetailVO.getEffectiveEndDate()) ) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        //公示期必须大于10天，当前时间和生效开始日期相差大于十天
        int flag = checkDate(scoreDetailVO.getEffectiveBeginTime());
        if (1 == flag) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "公示期最少10天，请选择十天后的时间！");
        }
        scoreDetailVO.setAdder(loginName);
        scoreDetailVO.setApproverTime(DateFormatUtil.getNow());
        //获取当前用户的dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isBlank(dicCode)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }

        //如果为区管理账号
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            scoreDetailVO.setState(NumberEnum.NINE.getNum());
            managerDao.addScore(scoreDetailVO);
            if (scoreDetailVO.getId() > NumberEnum.ZERO.getNum()) {
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        managerDao.addScore(scoreDetailVO);
        if (scoreDetailVO.getId() > NumberEnum.ZERO.getNum()) {
            Date publicBegin = new Date();
            Date publicEnd = null;
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            try{
                publicEnd = df.parse(scoreDetailVO.getEffectiveBeginTime());
            }catch (ParseException e){
                e.printStackTrace();
            }
            int ret = managerDao.publicity(loginName, scoreDetailVO.getId(), publicBegin, publicEnd);
            if (ret > NumberEnum.ZERO.getNum()) {
                //重新计算企业分数
                scoreUtil.updateRecord(scoreDetailVO.getCorpId());
                //新增通知消息
                addMsg(scoreDetailVO.getInfoType(), scoreDetailVO.getState(), loginName, scoreDetailVO.getCorpId());
                return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 公示
     *
     * @param loginName 登录名
     * @param id        id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    //TODO
    public CommonResult publicity(String loginName, Integer id){
        ScoreDetailVO sd = managerDao.findScoreDetailById(id);
        if (sd == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.RECORD_NOT_EXIST);
        }
        if (sd.getInfoType() == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), Common.PLEASE_INTRODUCTION_INFOTYPE);
        }
        //获取当前用户的dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isBlank(dicCode)) {
            return new CommonResult(ResultEnum.FAIL.getCode(),Common.OPERATE_FAIL);
        }
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            //如果为区管理账号
            int ret = managerDao.spNo(id,NumberEnum.NINE.getNum(),sd.getRemark(),loginName,null,null,null);
            if (ret > NumberEnum.ZERO.getNum()) {
                return new CommonResult(ResultEnum.SUCCESS.getCode(),Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(),Common.OPERATE_FAIL);
        }
        //查询当前记录的生效开始时间
        String beginTime = managerDao.getEffectiveBeginTimeById(id);
        String maxDate = beginTime;
        if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum()))) {
            //如果市级账号
            String fetureDate = getFetureDate(10);
            //比较生效时间和公示时间+10天的大小，取最大时间
            maxDate = getMaxDate(beginTime, fetureDate);
        }
        //公示结束日期,同生效开始时间
        Date publicEnd = null;
        //公示开始日期
        Date publicBegin = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try{
            publicEnd = df.parse(maxDate);
        }catch (ParseException e){
            e.printStackTrace();
        }

        int ret = managerDao.publicity(loginName, id, publicBegin, publicEnd);
        if (ret > NumberEnum.ZERO.getNum()) {
            //新增通知消息               2
            addMsg(sd.getInfoType(), NumberEnum.TWO.getNum(), loginName, sd.getCorpId());
            //重新计算分数
            scoreUtil.updateRecord(sd.getCorpId());
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 审批优良/负面信息
     *
     * @param loginName          登录名
     * @param id                 数据id
     * @param corpId             企业id
     * @param score              得分
     * @param scoreTypeId        得分类型id
     * @param effectiveBeginTime 生效开始时间
     * @param effectiveEndTime   生效结束时间
     * @param remark             备注
     * @param state              状态
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized CommonResult sp(String loginName, Integer id, Integer corpId,
                                        Integer scoreTypeId, String score,
                                        String effectiveBeginTime, String effectiveEndTime,
                                        String remark, Integer state,String backType) {

        //获取当前数据的详细信息
        ScoreDetailVO scoreDetail = managerDao.findScoreDetailById(id);
        //判断这条数据是否已被其他同级用户操作过
        if (scoreDetail.getState() != null) {
            //如果状态不为1、9、11,则表示该信息已经被处理
            if (!scoreDetail.getState().equals(NumberEnum.ONE.getNum())&&!scoreDetail.getState().equals(NumberEnum.NINE.getNum())&&!scoreDetail.getState().equals(NumberEnum.ELEVEN.getNum())) {
                return new CommonResult(ResultEnum.FAIL.getCode(), "该记录已经被处理");
            }
        } else {
            return new CommonResult(ResultEnum.FAIL.getCode(), "系统繁忙，请稍后重试");
        }
        //审核失败
        if (state.equals(NumberEnum.THREE.getNum())) {
            //判断回退位置 backType backType   1主管   2企业
            if(String.valueOf(NumberEnum.ONE.getNum()).equals(backType)){
                state = NumberEnum.ELEVEN.getNum();
            }
            //审核失败
            int ret = managerDao.spNo(id,state,remark,loginName,null,null,null);
            if (ret > NumberEnum.ZERO.getNum()) {
                addMsg(scoreDetail.getInfoType(), Common.THREE, loginName, scoreDetail.getCorpId());
                return new CommonResult(ResultEnum.SUCCESS.getCode(),Common.OPERATE_SUCCESS);
            }
            return new CommonResult(ResultEnum.FAIL.getCode(),Common.OPERATE_FAIL);
        } else if (state.equals(NumberEnum.TWO.getNum())) {
            //审批通过
            return approve(loginName, id, scoreTypeId, score, effectiveBeginTime, effectiveEndTime, remark, state, scoreDetail);
        }
        return  new CommonResult(ResultEnum.FAIL.getCode(),Common.OPERATE_FAIL);
    }

    /**
     * 审批通过
     * @return CommonResult
     */
    //TODO
    private CommonResult approve(String loginName, Integer id,
                                 Integer scoreTypeId, String score,
                                 String effectiveBeginTime, String effectiveEndTime,
                                 String remark, Integer state, ScoreDetailVO scoreDetail){
        //获取当前用户的dicCode
        String dicCode = managerDao.getDicCodeByLoginName(loginName);
        if (StringUtils.isBlank(dicCode)) {
            return new CommonResult(ResultEnum.FAIL.getCode(),Common.OPERATE_FAIL);
        }
        //判断开始时间是否为空
        if (StringUtils.isBlank(effectiveBeginTime) || StringUtils.isBlank(effectiveEndTime) ) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "有效期限请选择完整！");
        }
        //审核标记
        int ret = 0;
        String maxDate = effectiveBeginTime;
        //如果区级账号，判断开始时间是否为空，开始时间需要大于当前时间+10天
        if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
            //公示期必须大于10天，当前时间和生效开始日期相差大于十天
            int flag = checkDate(effectiveBeginTime);
            if (1 == flag) {
                return new CommonResult(ResultEnum.FAIL.getCode(), "公示期最少10天，请选择十天后的时间！");
            }
            state = NumberEnum.NINE.getNum();
        }else  if (dicCode.equals(String.valueOf(NumberEnum.THREE.getNum()))) {
            //如果市级账号
            String fetureDate = getFetureDate(10);
            //比较生效时间和市审核时间+10天的大小，取最大时间
            maxDate = getMaxDate(effectiveBeginTime, fetureDate);
            state = NumberEnum.TWO.getNum();
        }else if (dicCode.equals(String.valueOf(NumberEnum.ONE_HUNDRED.getNum()))) {
            //如果admin
            //查询审核状态 1-区审核中 9-市审核中
            String s = managerDao.getStateById(id);
            state = NumberEnum.TWO.getNum();
            if(String.valueOf(NumberEnum.ONE.getNum()).equals(s)){
                //公示期必须大于10天，当前时间和生效开始日期相差大于十天
                int flag = checkDate(effectiveBeginTime);
                if (1 == flag) {
                    return new CommonResult(ResultEnum.FAIL.getCode(), "公示期最少10天，请选择十天后的时间！");
                }
            }else if(String.valueOf(NumberEnum.NINE.getNum()).equals(s)){
                //比较前端传来的生效开始时间和当前时间+10天，取最大值
                String fetureDate = getFetureDate(10);
                //比较生效时间和市审核时间+10天的大小，取最大时间
                maxDate = getMaxDate(effectiveBeginTime, fetureDate);
            }
        }
        ret = managerDao.sp(id, score, scoreTypeId, maxDate, effectiveEndTime, remark, loginName, state);
        if (ret > Integer.parseInt(Common.ZERO)) {
            addMsg(scoreDetail.getInfoType(), Integer.parseInt(Common.TWO), loginName, scoreDetail.getCorpId());
            return new CommonResult(ResultEnum.SUCCESS.getCode(),Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 检查时间是否小于当前时间+10天
     * @param effectiveBeginTime
     * @return
     */
    public static int checkDate(String effectiveBeginTime){
        int flag = NumberEnum.ZERO.getNum();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        //当前日期
        Date nowDate = new Date();
        //前端传过来的生效开始时间effectiveBeginTime
        Date beginTime = null;
        try {
            beginTime = df.parse(effectiveBeginTime);
        }catch (ParseException e){
            e.printStackTrace();
        }
        int difNum = daydiff(nowDate, beginTime);
        if (difNum <= Common.TEN) {
            flag = NumberEnum.ONE.getNum();
        }
        return flag;
    }

    /**
     * 比较两个日期的大小，并返回最大时间
     * @param date1
     * @param date2
     * @return
     * @throws ParseException
     */
    public static String getMaxDate(String date1,String date2){
        String maxDate = date1;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = df.parse(date1);
            d2 = df.parse(date2);
        }catch (ParseException e){
            e.printStackTrace();
        }
        if(d1.getTime() < d2.getTime()){
            maxDate = date2;
        }
        return maxDate;
    }

    /**
     * 获取未来 第 past 天的日期
     * @param past
     * @return
     */
    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }


    /**
     * 变更优良/负面信息
     *
     * @param scoreDetailVO 参数
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult biangeng(ScoreDetailVO scoreDetailVO, String loginName,String backType) {
        ScoreDetailVO scoreDetail = managerDao.findScoreDetailById(scoreDetailVO.getId());
        if (scoreDetail.getState() != null) {
            if (!scoreDetail.getState().equals(NumberEnum.FOUR.getNum())&&!scoreDetail.getState().equals(NumberEnum.TEN.getNum())&&!scoreDetail.getState().equals(NumberEnum.TWELVE.getNum())) {
                return new CommonResult(ResultEnum.FAIL.getCode(), "该记录已经被处理");
            }
        } else {
            return new CommonResult(ResultEnum.FAIL.getCode(), "系统繁忙，请稍后重试");
        }
        //如果审批不通过
        if (scoreDetailVO.getState().equals(NumberEnum.FIVE.getNum())) {
            //获取当前用户的dicCode
            String dicCode = managerDao.getDicCodeByLoginName(loginName);
            if (StringUtils.isBlank(dicCode)) {
                return new CommonResult(ResultEnum.FAIL.getCode(),Common.OPERATE_FAIL);
            }
            //如果为区管理账号
            if (dicCode.equals(String.valueOf(NumberEnum.FOUR.getNum()))) {
                int ret = managerDao.spNo(scoreDetailVO.getId(),NumberEnum.TEN.getNum(),scoreDetailVO.getRemark(),loginName,scoreDetailVO.getSsnr(),String.valueOf(scoreDetailVO.getScore()),scoreDetailVO.getScoreTypeId());
                if (ret > NumberEnum.ZERO.getNum()) {
                    return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
                }
                return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
            }
        }
        scoreDetailVO.setScore(scoreDetailVO.getScore().abs());
        //修改企业得分信息   backType   1主管   2企业
        if(String.valueOf(NumberEnum.ONE.getNum()).equals(backType)){
            scoreDetailVO.setState(NumberEnum.TWELVE.getNum());
        }
        int num = managerDao.biangeng(scoreDetailVO);
        if (!scoreDetailVO.getState().equals(NumberEnum.SIX.getNum() )) {
            //如果审批通过则重新计算并修改该企业的得分信息
            scoreUtil.updateRecord(scoreDetailVO.getCorpId());
        }
        if (num > Integer.parseInt(Common.ZERO)) {
            //增加通知消息
            if (scoreDetail.getInfoType() != null && scoreDetail.getState() != null && scoreDetail.getCorpId() != null) {
                addMsg(scoreDetail.getInfoType(), scoreDetailVO.getState(), loginName, scoreDetail.getCorpId());
            }
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

    /**
     * 新增消息
     *
     * @param infoType  消息类型（1优良信息，2负面信息，3严重负面信息）
     * @param state     消息状态 (0-黑名单失效，1-黑名单生效，2-公示，3-审核不通过，
     *                  5-申诉成功，6-申诉失败，8-失效)
     * @param loginName 登录名
     * @param corpId    企业id
     */
    public void addMsg(Integer infoType, Integer state, String loginName, Integer corpId) {
        Message message = new Message();
        message.setType(infoType);
        if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.LOSE_EFFECT.getCode()) {
            //优良信息失效 infoType 1，state 8，url 优良查询界面
            message.setTitle(MessageEnum.IS_LOSE_YOULIANG.getMsg());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.PASS_THROUGH.getCode()) {
            //优良信息审核通过/公示  infoType 1，state 2，url 优良录入界面
            message.setTitle(MessageEnum.IS_PASS_YOULIANG.getMsg());
            message.setUrl(UrlEnum.ADD_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.NOT_THROUGH.getCode()) {
            //优良信息审核不通过  infoType 1，state 3，url 优良查询界面
            message.setTitle(MessageEnum.IS_NO_PASS_YOULIANG.getMsg());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.APPEAL_SUCCESS.getCode()) {
            //优良信息申诉通过  infoType 1，state 5，url 优良查询界面
            message.setTitle(MessageEnum.GOOD_INFO_APPEAL.getMsg());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.EXCELLENT.getCode() && state == StateEnum.APPEAL_FAIL.getCode()) {
            //优良信息申诉未通过  infoType 1，state 6，url 优良查询界面
            message.setTitle(MessageEnum.GOOD_INFO_NO_APPEAL.getMsg());
            message.setUrl(UrlEnum.QUERY_GOOD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.LOSE_EFFECT.getCode()) {
            //负面信息审核失效  infoType 2，state 8，url 负面查询界面
            message.setTitle(MessageEnum.IS_LOSE_FUMIAN.getMsg());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.PASS_THROUGH.getCode()) {
            //负面信息审核通过/公示  infoType 2，state 2，url 负面录入界面
            message.setTitle(MessageEnum.IS_PASS_FUMIAN.getMsg());
            message.setUrl(UrlEnum.ADD_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.NOT_THROUGH.getCode()) {
            //负面信息审核不通过  infoType 2，state 3，url 负面查询界面
            message.setTitle(MessageEnum.IS_NO_PASS_FUMIAN.getMsg());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.APPEAL_SUCCESS.getCode()) {
            //负面信息申诉通过  infoType 2，state 5，url 负面查询界面
            message.setTitle(MessageEnum.BAD_INFO_APPEAL.getMsg());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.NEGATIVE.getCode() && state == StateEnum.APPEAL_FAIL.getCode()) {
            //负面信息申诉未通过  infoType 2，state 6，url 负面查询界面
            message.setTitle(MessageEnum.BAD_INFO_NO_APPEAL.getMsg());
            message.setUrl(UrlEnum.QUERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.SERIOUS_NEGATIVE.getCode() && state == StateEnum.TACK_EFFECT.getCode()) {
            //黑名单生效  infoType 3，state 1，url 黑名单界面
            message.setTitle(MessageEnum.IS_ADD_BLACKLIST.getMsg());
            message.setUrl(UrlEnum.VERY_BAD_INFO.getUrl());
        } else if (infoType == InfoTypeEnum.SERIOUS_NEGATIVE.getCode() && state == StateEnum.LOSE_EFFICACY.getCode()) {
            //黑名单失效  infoType 3，state 0，url 黑名单界面
            message.setTitle(MessageEnum.IS_REMOVE_BLACKLIST.getMsg());
            message.setUrl(UrlEnum.VERY_BAD_INFO.getUrl());
        }
        message.setAdder(loginName);
        message.setCropid(corpId);
        messageDao.addMessage(message);
    }

    /**
     * 计算两个日期相差天数
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    public static int daydiff(Date beginDate, Date endDate) {
        Calendar aCalendar = Calendar.getInstance();
        //开始日期
        aCalendar.setTime(beginDate);
        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
        int year1 = aCalendar.get(Calendar.YEAR);
        //结束日期
        aCalendar.setTime(endDate);
        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
        int year2 = aCalendar.get(Calendar.YEAR);
        //如果是在同一年
        if (year1 == year2) {
            return day2 - day1;
        } else {
            //如果不在同一年
            int day = (year2 - year1) * 365;
            return day2 - day1 + day;
        }
    }

}
